package com.hust360.percent;

import java.io.File;
import java.io.IOException;
import org.apache.http.HttpConnection;
import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.DefaultHttpClient;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.hust360.percent.local_db.LocalDBHelper;
import com.hust360.percent.pojo.AreaDAO;
import com.hust360.percent.pojo.AreaDAOImpl;
import com.hust360.percent.pojo.City;
import com.hust360.percent.pojo.DiscountInfoDAO;
import com.hust360.percent.pojo.DiscountInfoDAOImpl;
import com.hust360.percent.pojo.ShopDAO;
import com.hust360.percent.pojo.ShopDAOImpl;
import com.hust360.percent.utils.PercentThreadPool;
import com.hust360.percent.utils.StorageUtils;

import android.app.Application;
import android.content.SharedPreferences;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import android.widget.Toast;

/**
 *  
 *
 */
public class PercentApplication extends Application {
	
	/**
	 * TAG FOR DDMS LOGCAT
	 */
	public static final String TAG = "PercentApplication";
	
	private City curCity;
	
	/**
	 * 屏幕像素密度
	 */
	private float density;

	/**
	 * 网络访问所用的线程池
	 */
	private PercentThreadPool threadPool;

	/**
	 * baidu 定位api
	 */
	private LocationClient locClient;

	/**
	 * 定位监听器
	 */
	private BDLocationListener locListener;

	/**
	 * 用户当前的经度
	 */
	private double longitude = 0;

	/**
	 * 用户当前的纬度
	 */
	private double latitude = 0;

	/**
	 * 获取位置成功的标志
	 */
	private boolean hasPoc = false;

	/**
	 * 
	 */
	public static final long REQUST_CODE = 0;

	/**
	 * 程序的sharedPerferences的名字
	 */
	public static final String SHARED_PREFERENCES_NAME = "percent_shared_preferences";

	/**
	 * 检测程序是否是第一次运行的shareperferences的key
	 */
	public static final String APP_IS_FIRST_RUN = "app_is_first_run";

	public static final int WRITE_SDCARD_FAILED = -2;

	/**
	 * 程序在sd卡中的缓存文件夹的绝对路径
	 */
	public static String baseFolder = "";

	/**
	 * SD卡中，图片缓存文件夹的绝对路径
	 */
	public static String baseImageFolder = "";

	/**
	 * 应用程序的SharedPreferences
	 */
	SharedPreferences sharedPreferences;

	/**
	 * 与服务器连接的http连接类
	 */
	HttpConnection httpConnection;

	/** 整个应用中使用的连接服务器的httpClient */
	HttpClient httpClient;

	/**
	 * 本地数据库的database helper
	 */
	LocalDBHelper localDBHelper;

	/**
	 * 本地数据实例
	 */
	SQLiteDatabase localDB;

	/**
	 * 用来操作本地数据库的ShopDao的接口
	 */
	private ShopDAO shopDao;
	
	/**
	 * 用来操作本地数据的AreaDAO的接口
	 */
	private AreaDAO areaDAO;

	/**
	 * discountInfo的接口
	 */
	private DiscountInfoDAO discountInfoDAO;
	
	/**
	 * 记录城市列表的数据库的实例
	 */
	private SQLiteDatabase cityDB;

	@Override
	public void onCreate() {
		super.onCreate();

		try {
			
			density = getResources().getDisplayMetrics().density;
			
			/**
			 * 默认城市
			 */
			curCity = new City();
			curCity.name = "武汉";
			curCity.id = 4201L;
			curCity.province = 42L;
			
			Log.i(TAG, "density is : " + density );
			/*
			 * 初始化线程池
			 */
			threadPool = new PercentThreadPool();
			
			/*
			 * 初始化城市查找的数据库对象
			 */
			// 已经把代码移动到WelcomeActiviy中或者FirstRunActivity中进行
			
			/*
			 * 初始化定位资源
			 */
			locClient = new LocationClient(getApplicationContext());
			if (locClient != null) {
				LocationClientOption option = new LocationClientOption();
				option.setProdName("com.hust.percent");
				option.setScanSpan(5000); // 请求间隔
				option.setPriority(LocationClientOption.NetWorkFirst); // 网络定位优先

				locListener = new PercentLocListener();
				locClient.registerLocationListener(locListener);
				locClient.setLocOption(option);
				locClient.start();
				locClient.requestLocation();

			}


			/*
			 * 初始化数据库对象
			 */
			StorageUtils.buildLocalDataDirectory();
			baseFolder = StorageUtils.getSDPath() + File.separator
					+ StorageUtils.SDCARD_BASE_FOLDER;

			baseImageFolder = baseFolder + File.separator
					+ StorageUtils.SDCARD_IMG_FOLDER;

			String path = baseFolder + File.separator
					+ StorageUtils.SDCARD_DB_NAME;
			localDBHelper = new LocalDBHelper(getApplicationContext(), path,
					null, 1);
			localDB = localDBHelper.getWritableDatabase();

			shopDao = new ShopDAOImpl(this);
			discountInfoDAO = new DiscountInfoDAOImpl(this);
			areaDAO = new AreaDAOImpl(this);

			/*
			 * 初始化网络访问对象
			 */
			httpClient = new DefaultHttpClient();

			/*
			 * 获取程序的sharedPreferences
			 */
			sharedPreferences = getSharedPreferences(SHARED_PREFERENCES_NAME,
					MODE_PRIVATE);

			/*
			 * 获取主键id当前最大值
			 */
			StorageUtils.curMaxShopId = sharedPreferences.getLong(
					StorageUtils.CUR_MAX_SHOP_ID_KEY, 0);
			StorageUtils.curMaxDiscountId = sharedPreferences.getLong(
					StorageUtils.CUR_MAX_DISCOUNT_ID_KEY, 0);
			

		} catch (IOException e) {
			e.printStackTrace();
			Toast.makeText(getApplicationContext(), "初始化数据失败,请确认SD卡是否插入或已挂载",
					Toast.LENGTH_SHORT).show();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	public SharedPreferences getSharedPreferences() {
		return sharedPreferences;
	}

	public void setSharedPreferences(SharedPreferences sharedPreferences) {
		this.sharedPreferences = sharedPreferences;
	}

	public HttpConnection getHttpConnection() {
		return httpConnection;
	}

	public void setHttpConnection(HttpConnection httpConnection) {
		this.httpConnection = httpConnection;
	}

	public HttpClient getHttpClient() {
		return httpClient;
	}

	public void setHttpClient(HttpClient httpClient) {
		this.httpClient = httpClient;
	}

	public LocalDBHelper getLocalDBHelper() {
		return localDBHelper;
	}

	public void setLocalDBHelper(LocalDBHelper localDBHelper) {
		this.localDBHelper = localDBHelper;
	}

	public SQLiteDatabase getLocalDB() {
		return localDB;
	}

	public void setLocalDB(SQLiteDatabase localDB) {
		this.localDB = localDB;
	}

	public ShopDAO getShopDao() {
		return shopDao;
	}


	public DiscountInfoDAO getDiscountInfoDAO() {
		return discountInfoDAO;
	}


	public double getLongitude() {
		return longitude;
	}

	/**
	 * 设置经度
	 * 
	 * @param longitude
	 */
	public void setLongitude(double longitude) {
		this.longitude = longitude;
	}

	public double getLatitude() {
		return latitude;
	}

	/**
	 * 设置纬度
	 * 
	 * @param latitude
	 */
	public void setLatitude(double latitude) {
		this.latitude = latitude;
	}

	public boolean isHasPoc() {
		return hasPoc;
	}

	public void setHasPoc(boolean hasPoc) {
		this.hasPoc = hasPoc;
	}

	public PercentThreadPool getThreadPool() {
		return threadPool;
	}

	public SQLiteDatabase getCityDB() {
		return cityDB;
	}

	public void setCityDB(SQLiteDatabase cityDB) {
		this.cityDB = cityDB;
	}

	public City getCurCity() {
		return curCity;
	}
	
	public void setCurCity(City city) {
		curCity = city;
	}

	public float getDensity() {
		return density;
	}

	public AreaDAO getAreaDAO() {
		return areaDAO;
	}

	public void setAreaDAO(AreaDAO areaDAO) {
		this.areaDAO = areaDAO;
	}

	private class PercentLocListener implements BDLocationListener {

		@Override
		public void onReceiveLocation(BDLocation arg0) {
			int type = arg0.getLocType();
			if (type == 61 || type == 161) {
				longitude = arg0.getLongitude();
				latitude = arg0.getLatitude();
				hasPoc = true;
			}
		}

		@Override
		public void onReceivePoi(BDLocation arg0) {
			// TODO Auto-generated method stub

		}

	}

}
